from flask import current_app, request

from flask_restful.reqparse import RequestParser


class Page(object):
    """
        基于sqlalchemy的分页组件
    """
    page_parser = RequestParser()
    page_parser.add_argument('page', type=int, default=1)
    page_parser.add_argument('size', type=int, default=10)

    def __init__(self, sqlalchemy_query, object_class=None, entity_class=None, value_object_class=None):
        self.entity_class = entity_class
        self.value_object_class = value_object_class
        args = self.page_parser.parse_args()
        self.page = args["page"]  # 查询的页码
        self.size = args["size"]  # 每页的大小
        if object_class:
            sqlalchemy_query = sqlalchemy_query.order_by(object_class.id.desc())
        self.sqlalchemy_query = sqlalchemy_query.paginate(page=self.page,
                                                          per_page=self.size,
                                                          error_out=False,
                                                          max_per_page=50)

    def count(self):
        return self.sqlalchemy_query.total

    def page_info(self):
        """
        """
        return {
            "total": self.sqlalchemy_query.total,
            "pages": self.sqlalchemy_query.pages,
            "page": self.sqlalchemy_query.page,
            "size": self.size
        }

    @property
    def items(self):
        """
            返回查询的集合列表
        """
        if self.entity_class:
            items = map(lambda x: self.entity_class(x), self.sqlalchemy_query.items)

        elif self.value_object_class:
            items = map(lambda x: self.value_object_class(**dict(zip(x.keys(), x))), self.sqlalchemy_query.items)
        else:
            items = self.sqlalchemy_query.items

        return items


def get_count_from_query():
    count_default = current_app.config.get("COUNT_DEFAULT")
    count = int(request.args.get("count", count_default if count_default else 1))
    return count


def get_page_from_query():
    page_default = current_app.config.get("PAGE_DEFAULT")
    page = int(request.args.get("page", page_default if page_default else 0))
    return page


def paginate():
    from lin.exception import ParameterError

    count = int(
        request.args.get(
            "count",
            current_app.config.get("COUNT_DEFAULT")
            if current_app.config.get("COUNT_DEFAULT")
            else 5,
        )
    )
    start = int(
        request.args.get(
            "page",
            current_app.config.get("PAGE_DEFAULT")
            if current_app.config.get("PAGE_DEFAULT")
            else 0,
        )
    )
    count = 15 if count >= 15 else count
    start = start * count
    if start < 0 or count < 0:
        raise ParameterError()
    return start, count
